package com.ruoyi.web.controller.cs;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.banbeiPay.Disguiser;
import com.ruoyi.common.banbeiPay.HttpClientService;
import com.ruoyi.common.banbeiPay.MyBeanUtils;
import com.ruoyi.common.banbeiPay.MyDateUtils;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BasicsController;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.utils.bean.*;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.pay.FXPayConfig;
import com.ruoyi.common.utils.pay.MD5;
import com.ruoyi.common.utils.pay.SignUtils;
import org.apache.commons.httpclient.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@RestController
@RequestMapping("/cs/zftest")
@SuppressWarnings("all")
public class ZFTestController extends BasicsController {
    private static Logger log = LoggerFactory.getLogger(ZFTestController.class);

    //下单请求地址
    private static String unifiedorder = "http://8.129.177.76:8088/dopay/unifiedorder";

    //查询地址
    private static String orderquery = "http://47.115.11.116:8080/dopay/orderquery";
    // 测试账号
    private static String mch_id = "3658206";
    private static String key = "2e02dfe0adc2cb8919f99cee8560ccf7";



    /**富信支付*/

    /**
     * 组装请求参数
     *
     * @param map
     * @return
     */
    private static String hxPay(String orderid) {
        Map<String, String> map = new HashMap<>();
        map.put("sdorderno", orderid);
        map.put("appid", FXPayConfig.applyId);
        map.put("goods_id", "8361");
        map.put("sign", SignUtils.signFXNotify(map, FXPayConfig.applykey));
        map.put("paytype", "alipaywap");
        map.put("time", System.currentTimeMillis()+"");
        map.put("buyers", "ssss");
        map.put("client_ip", "111.1.97.167");
        map.put("steam_url", null);
        System.out.println("【请求参数】：" + map.toString());
        String result = HttpUtils.http(FXPayConfig.applyPay,map);
        JSONObject jsonObject = JSON.parseObject(result);
        if(jsonObject.getInteger("status") == 200){
            return jsonObject.getString("result");
        }
        return  result;
    }

    private static String fxQuery(String orderid) {
        Map<String, String> map = new HashMap<>();
        map.put("sdorderno", orderid);
        map.put("appid", FXPayConfig.applyId);
        map.put("goods_id", "8360");
//        map.put("buyer", "0");
        map.put("sign", SignUtils.signFXQuery(map, FXPayConfig.applykey));
        System.out.println("【请求参数】：" + map.toString());
        String result = HttpUtils.http(FXPayConfig.applyQuery,map);
        JSONObject jsonObject = JSON.parseObject(result);
        if(jsonObject.getInteger("status") == 200){
            return jsonObject.getString("result");
        }
        return  result;
    }


//    public static void main(String[] args) {
//        System.out.println(hxPay("1233332312"));
//    }

    /**
     * 生成签名字段
     *
     * @param map
     * @return
     */
    private static String buildHxSign(TreeMap<String, String> map, String key) {
        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        String sign = MD5.sign(preStr, "&secret=" + key, "utf-8");
        return sign;
    }


    @RequestMapping(name="传化支付交易",value="common/grate",method = RequestMethod.GET)
    public Response<Object> goodsListByBoxId(String orderid){
        TreeMap<String, String> treeMap = buildDoPay(orderid);
        String sign = buildSign(treeMap,key);


        return null;
    }

    /**
     * 组装请求参数
     *
     * @param map
     * @return
     */
    private static TreeMap<String, String> buildDoPay(String orderid) {
        TreeMap<String, String> map = new TreeMap<String, String>();
        map.put("mch_id", mch_id);   //1必填 商户号
        map.put("body", "游戏充值");     //2必填 商品名称
        map.put("trade_type", "ALIPAY.FTF");// 3必填
        map.put("total_fee", "10"); //4必填 支付金额 分为单位
        map.put("out_trade_no", orderid);  //5交易单号
        map.put("notify_url", "http://www.baidu.com");                 //6必填 回调通知地址；
        map.put("return_url", "http://www.baidu.com");              //7非必填  交易成功返回地址 ALIPAY.WEB的时需要
        map.put("sign", buildSign(map, key));  //8必填 签名
        System.out.println("【请求参数】：" + map.toString());
        return map;
    }




    /**
     * 生成签名字段
     *
     * @param map
     * @return
     */
    private static String buildSign(TreeMap<String, String> map, String key) {
        Map<String, String> params = SignUtils.paraFilter(map);
        StringBuilder buf = new StringBuilder((params.size() + 1) * 10);
        SignUtils.buildPayParams(buf, params, false);
        String preStr = buf.toString();
        String sign = MD5.sign(preStr, "&key=" + key, "utf-8");
        return sign;
    }


//    public static void main(String[] args) {
//        String orderId = UUID.randomUUID().toString().substring(0,10);
////        String orderId = "111111";
//        String str = HttpUtils.http(unifiedorder, buildDoPay(orderId));
//        System.out.println("【下单返回参数】：" + str);
//
//        //返回验签
//        JSONObject result;
//        try {
//            result = JSON.parseObject(str);
//            JSONObject signObj =  result.getJSONObject("params_info");
//            String sign = result.getString("sign");
//            String paramsStr = SignUtils.getSortJson(signObj);
//            String mchSign = SignUtils.buildStrSign(paramsStr, key);
//            System.out.println(mchSign+"----->"+sign);
//            if (mchSign.equals(sign)) {
//
//                System.out.println("【下单验签成功】：" + result.toJSONString());
//
//            } else {
//                System.out.println("【下单验签失败】：" + result.toJSONString());
//            }
//
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//
//        /**查询订单*/
//        qureyOrder(orderId);
//
//    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        String mch_id = request.getParameter("mch_id");
        String order_no = request.getParameter("order_no");
        String total_fee = request.getParameter("total_fee");
        String order_status = request.getParameter("order_status");
        String order_status_desc = request.getParameter("order_status_desc");
        String out_trade_no = request.getParameter("out_trade_no");
        String pay_time = request.getParameter("pay_time");
        String trade_type = request.getParameter("trade_type");
        String sign = request.getParameter("sign");
        String body = request.getParameter("body");

        final TreeMap<String, String> paramsMap = new TreeMap<String, String>();
        paramsMap.put("mch_id", mch_id);
        paramsMap.put("order_no", order_no);
        paramsMap.put("out_trade_no", out_trade_no);
        paramsMap.put("total_fee", total_fee);
        paramsMap.put("trade_type", trade_type);
        paramsMap.put("order_status", order_status);
        paramsMap.put("order_status_desc", order_status_desc);
        paramsMap.put("body", body);
        paramsMap.put("pay_time", pay_time);

        String mchSign = SignUtils.buildMapSign(paramsMap, key);
        PrintWriter out = response.getWriter();

        if (mchSign.equals(sign)) {
            out.write("SUCCESS");
            System.out.println("【通知验签成功】：" + paramsMap.toString());
        } else {
            out.write("FAIL");
            System.out.println("【通知验签失败】：" + paramsMap.toString());
        }
        out.flush();
        out.close();
    }

    /**
     * 组装查询参数
     *
     * @param map
     * @return
     */
    private static TreeMap<String, String> buildDoQuery(String orderid) {
        TreeMap<String, String> map = new TreeMap<String, String>();
        map.put("mch_id", mch_id);                          //必填 商户编号
        map.put("out_trade_no",orderid);           //必填 商户订单号
//        map.put("order_no", "80120181008001259532882361");  //可选 平台订单号
        map.put("sign", buildSign(map, key));               //必填 签名参数
        System.out.println("【查询请求参数】：" + map.toString());
        return map;
    }

    public static void qureyOrder(String orderid){
        String str = HttpUtils.http(orderquery, buildDoQuery(orderid));
        System.out.println("【查询返回参数】：" + str);
        //返回验签

        JSONObject result;
        try {
            result = JSON.parseObject(str);
            JSONObject signObj =  result.getJSONObject("params_info");
            String payFrom = signObj.getString("pay_info");
            String mch_id = signObj.getString("mch_id");
            String order_no = signObj.getString("order_no");
            String out_trade_no = signObj.getString("out_trade_no");
            String total_fee = signObj.getString("total_fee");
            String trade_type = signObj.getString("trade_type");
            String order_status = signObj.getString("order_status");
            String order_status_desc = signObj.getString("order_status_desc");
            String sign = result.getString("sign");

            JSONObject paramsMap = new JSONObject();
            paramsMap.put("mch_id", mch_id);
            paramsMap.put("order_no", order_no);
            paramsMap.put("out_trade_no", out_trade_no);
            paramsMap.put("total_fee", total_fee);
            paramsMap.put("trade_type", trade_type);
            paramsMap.put("order_status", order_status);
            paramsMap.put("order_status_desc", order_status_desc);

            String paramsStr = SignUtils.getSortJson(paramsMap);
            String mchSign = SignUtils.buildStrSign(paramsStr, key);

            if (mchSign.equals(sign)) {

                System.out.println("【查询验签成功】：" +  result.toJSONString());

            } else {
                System.out.println("【查询验签失败】：" +  result.toJSONString());
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/common/createOrder")
    public String createOrder(String orderId) {
        boolean isSuccess = false;
        Map<String, Object> resultMap = null;
        try {
            AppCreateOrderVo orderVo = this.createOrderParam(orderId);
            Map<String, String> map = MyBeanUtils.convertBean(orderVo, new LinkedHashMap());
            String oriMessage = MyBeanUtils.getSignedByPresetParameter(map, AppCreateOrderVo.NEED_SIGN_PARAMS, false);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
            map.put("sign", sign);
            resultMap = HttpClientService.getHttpResp(map, Constants.REQUEST_URL);
            log.info("响应结果：" + resultMap);
            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                /*// 需要排除签名的,后续可能会增加*/
                String resultMsg = (String) resultMap.get("response");
                AppCreateOrderResponseVo orderResponseVo = JSONObject.parseObject(resultMsg, AppCreateOrderResponseVo.class);
                String assemblyRespOriSign = MyBeanUtils.getSignedByPresetParameter(orderResponseVo, AppCreateOrderResponseVo.NEED_SIGN_PARAMS, false);

                log.info("组装返回结果签名串：" + assemblyRespOriSign);
                String responseSign = orderResponseVo.getSign();

                JSONObject jsonObject = JSONObject.parseObject(resultMsg);
                log.info("返回订单信息：{}",jsonObject.toJSONString());

                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    if ("0000".equals(orderResponseVo.getRt2_retCode())) {
                        isSuccess = true;
                        log.info("创建帮呗支付订单成功！");
                        return jsonObject.toJSONString();
                    } else {
                        log.error("创建帮呗支付订单失败:平台订单号:{},返回信息:{}", orderResponseVo.getRt5_orderId(),orderResponseVo.getRt3_retMsg());
                    }
                } else {
                    log.error("订单接口验签失败,响应结果:{}，验签结果:{}",resultMsg,responseSign);
                }
            } else {
                log.error("创建订单失败！，返回结果:{}",resultMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("帮呗支付创建订单异常，异常信息:{},响应结果:{}",e.getMessage(),resultMap);
        }
        return "创建订单失败";
    }

    public AppCreateOrderVo createOrderParam(String orderid){
        AppCreateOrderVo orderVo = new AppCreateOrderVo();
        orderVo.setP1_bizType("AppPay");
        orderVo.setP2_orderId(orderid);
        orderVo.setP3_customerNumber(Constants.PA_MERCHANT_NO);
        orderVo.setP4_payType("SCAN");
        orderVo.setP5_orderAmount("0.01");
        orderVo.setP6_currency("CNY");
        orderVo.setP7_authcode("1");
        orderVo.setP8_appType("ALIPAY");
        orderVo.setP9_notifyUrl("https://wap.bangbeipay.com/notify.php");
        orderVo.setP10_successToUrl("https://wap.bangbeipay.com/success.php");
        orderVo.setP11_orderIp("60.180.136.56");
        orderVo.setP12_goodsName("1818skins");
        orderVo.setTimeExpire("20m");
        return orderVo;
    }

    @RequestMapping(value = "/common/queryOrder")
    public Map queryOrder(String orderId) {
        boolean isSuccess = false;
        try {
            QueryOrderVo queryOrderVo = this.createQueryOrderParam(orderId);
            Map<String, String> map = MyBeanUtils.convertBean(queryOrderVo, new LinkedHashMap());
            String oriMessage = MyBeanUtils.getSignedByPresetParameter(map, QueryOrderVo.NEED_SIGN_PARAMS, false);
            log.info("签名原文串：" + oriMessage);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
            log.info("签名串：" + sign);
            map.put("sign", sign);
            log.info("发送参数：" + map);
            Map<String, Object> resultMap = HttpClientService.getHttpResp(map, Constants.REQUEST_URL);
            log.info("响应结果：" + resultMap);
            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                QueryOrderResponseVo queryOrderResponseVo = JSONObject.parseObject(resultMsg, QueryOrderResponseVo.class);
                String assemblyRespOriSign = MyBeanUtils.getSignedByPresetParameter(queryOrderResponseVo, QueryOrderResponseVo.NEED_SIGN_PARAMS, false);
                logger.info("组装返回结果签名串：" + assemblyRespOriSign);
                String responseSign = queryOrderResponseVo.getSign();
                logger.info("响应签名：" + responseSign);
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    if ("0000".equals(queryOrderResponseVo.getRt2_retCode())) {
                        isSuccess = true;
                        log.info("订单查询接口请求成功");
                        JSONObject jsonObject = JSONObject.parseObject(resultMsg, JSONObject.class);
                        String rt7OrderStatus = jsonObject.getString("rt7_orderStatus");
                       return resultMap;
                    } else {
                        log.error("订单查询结果错误:{}", queryOrderResponseVo.getRt3_retMsg());
                    }
                } else {
                    log.error("订单查询结果验签不通过:{},签名:{]", resultMsg,checkSign);
                }
            } else {
               log.error("查询订单接口请求失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询订单接口异常:{}",e.getMessage());
        }
        return null;
    }

    public QueryOrderVo createQueryOrderParam(String orderid){
        QueryOrderVo orderVo = new QueryOrderVo();
        orderVo.setP1_bizType("AppPayQuery");
        orderVo.setP2_orderId(orderid);
        orderVo.setP3_customerNumber(Constants.PA_MERCHANT_NO);
        return orderVo;
    }


    @ResponseBody
    @RequestMapping(value = "/notify")
    public String notify(NotifyResponseVo notifyResponseVo, Model model) {
        try {
            String assemblyRespOriSign = MyBeanUtils.getSignedByPresetParameter(
                    notifyResponseVo, NotifyResponseVo.NEED_SIGN_PARAMS, false);
            logger.info("组装返回结果签名串：" + assemblyRespOriSign);
            String responseSign = notifyResponseVo.getSign();
            logger.info("响应签名：" + responseSign);
            String checkSign = Disguiser
                    .disguiseMD5(assemblyRespOriSign.trim());
            logger.info("验证签名：" + checkSign);
            if (checkSign.equals(responseSign)) {
                // 验证签名成功()
                // 商户根据根据支付结果做业务处理

                //
                return "success";// 反馈处理结果
            } else {
                return "fail 验证签名失败";
            }
        } catch (Exception e) {
            return "fail 系统内部错误" + e.getMessage();// 反馈处理结果
        }
    }

    @RequestMapping(value = "/common/transfer")
    public  Map<String, Object> transfer(String orderId,String amount) {
        logger.info("--------进入代付下单接口----------");
        boolean isSuccess = false;
        Map<String, Object> resultMap = null;
        try {
            TransferReqParam param = createTransferReqParam(orderId,amount);
            Map<String, String> map = MyBeanUtils.convertBean(param, new LinkedHashMap());
            String oriMessage = MyBeanUtils.getSignedByPresetParameter(map, TransferReqParam.NEED_SIGN_PARAMS, true);
            logger.info("宝和利代付下单签名原文串：" + oriMessage);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
            logger.info("宝和利代付下单签名串：" + sign);
            map.put("sign", sign);
            logger.info("宝和利代付下单发送参数：" + map);
            resultMap = HttpClientService.getHttpResp(map, Constants.TRANSFER_URL);
            logger.info("宝和利代付下单响应结果：" + resultMap);
            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                TransferResParam resParam = JSONObject.parseObject(resultMsg, TransferResParam.class);
                String assemblyRespOriSign = MyBeanUtils.getSignedByPresetParameter(resParam, TransferResParam.NEED_SIGN_PARAMS, true);
                logger.info("宝和利代付下单组装返回结果签名串：" + assemblyRespOriSign);
                String responseSign = resParam.getSign();
                logger.info("宝和利代付下单响应签名：" + responseSign);
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    final String rt3RetMsg = resParam.getRt3_retMsg();
                    logger.info("宝和利代付下单验签通过");
                    if ("0000".equals(resParam.getRt2_retCode())) {
                        isSuccess = true;
                        log.info("宝和利代付下单下单成功:{}",resultMsg);
                    } else {
                        log.error("宝和利代付下单返回失败", resParam.getRt5_orderId() + "-" + rt3RetMsg);
                    }
                } else {
                    log.error("宝和利代付验签失败", resultMsg);
                }
            } else {
                log.error("宝和利代付下单请求失败");
            }
        } catch (Exception e) {
            logger.error("transfer", e);
            log.error("宝和利代付下单交易异常：{}" + e.getMessage());
        }
        if (!isSuccess) {
            String format1 = MyDateUtils.format().format(new Date());
        }
        return resultMap;
    }

    public TransferReqParam createTransferReqParam(String orderid, String amount){
        TransferReqParam orderVo = new TransferReqParam();
        orderVo.setP1_bizType("Transfer");
        orderVo.setP2_orderId(orderid);
        orderVo.setP3_customerNumber(Constants.PA_MERCHANT_NO);
        orderVo.setP4_amount(amount);
        orderVo.setP5_bankCode("CCB");
        orderVo.setP6_bankAccountNo("6236681420028729374");
        orderVo.setP7_bankAccountName("王豪哲");
        orderVo.setP8_biz("B2C");
        orderVo.setP10_feeType("RECEIVER");
        orderVo.setP11_urgency("true");
        orderVo.setP12_summary("结算款");
        return orderVo;
    }

    @RequestMapping(value = "/common/transferQuery")
    public  Map<String, Object> transferQuery(String orderId) {
        logger.info("--------进入代付查询接口----------");
        boolean isSuccess = false;
        Map<String, Object> resultMap = null;
        try {
            TransferQueryReqParam param = createrTransferQueryReqParam(orderId);
            Map<String, String> map = MyBeanUtils.convertBean(param, new LinkedHashMap());
            String oriMessage = MyBeanUtils.getSignedByPresetParameter(map, TransferQueryReqParam.NEED_SIGN_PARAMS, true);
            logger.info("签名原文串：" + oriMessage);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
            logger.info("签名串：" + sign);
            map.put("sign", sign);
            logger.info("发送参数：" + map);
            resultMap = HttpClientService.getHttpResp(map, Constants.TRANSFER_URL);
            logger.info("响应结果：" + resultMap);
            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                TransferQueryResParam resParam = JSONObject.parseObject(resultMsg, TransferQueryResParam.class);
                String assemblyRespOriSign = MyBeanUtils.getSignedByPresetParameter(resParam, TransferQueryResParam.NEED_SIGN_PARAMS, true);
                logger.info("组装返回结果签名串：" + assemblyRespOriSign);
                String responseSign = resParam.getSign();
                logger.info("响应签名：" + responseSign);
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    final String rt3RetMsg = resParam.getRt3_retMsg();
                    logger.info("验签通过");
                    if ("0000".equals(resParam.getRt2_retCode())) {
                        isSuccess = true;
                        logger.info("宝和利代付查询成功:{}",resultMsg);
                    } else {
                        logger.error("宝和利代付查询返回失败", resParam.getRt5_orderId() + "-" + rt3RetMsg);
                    }
                } else {
                    logger.error("宝和利代付查询验签失败:{}", resultMsg);
                }
            } else {
                logger.error("宝和利代付查询请求失败");
            }
        } catch (Exception e) {
            logger.error("transferQuery", e);
            logger.error("宝和利代付查询异常:{}",e.getMessage());
        }
        if (!isSuccess) {
            String format1 = MyDateUtils.format().format(new Date());
        }
        return resultMap;
    }


    public TransferQueryReqParam createrTransferQueryReqParam(String orderid){
        TransferQueryReqParam orderVo = new TransferQueryReqParam();
        orderVo.setP1_bizType("TransferQuery");
        orderVo.setP2_orderId(orderid);
        orderVo.setP3_customerNumber(Constants.PA_MERCHANT_NO);
        return orderVo;
    }

}
